<?php

/**
 * Created by PhpStorm.
 * User: z
 * Date: 14-9-1
 * Time: 下午5:26
 */
class Supplierbank
{

    /**
     * 处理查询信息
     * 查询条件
     * 1.供应商ID
     * 2.供应商名称
     * 3.付款方式
     * 4.开户银行
     * 5.账户名称
     * 6.帐号
     * 7.
     * 8.
     * 9.
     * @pram array
     */
/*    public static function get_supplier_info(array $condtion = NULL)
    {
        $re = self::do_select($condtion);
        return self::datas_to_views($re);
    }*/

    /**
     * 出来数据库查询
     * @param array $condtion
     * @return null array
     */
    public static function do_select(array $condtion = NULL)
    {
        /*$select_head = array(
            array('supplierpayaccount.id','id'),
            array('supplierpayaccount.supplier_id','supplier_id'),
            array('supplierpayaccount.payways_id','payways_id'),
            array('supplierpayaccount.active_status','active_status'),
            array('supplierpayaccount.check_status','check_status'),
            array('supplierpayaccount.check_id','check_id'),
            array('supplierpayaccount.check_remark','check_remark'),
            array('payaccountinfo.bankname','bankname'),
            array('payaccountinfo.bankaccountname','bankaccountname'),
            array('payaccountinfo.bankaccount','bankaccount'),
            array('payways.paywayname','paywayname')payaccountinfo_id
        );*/
        $re = DB::select(array(
                'supplierpayaccount.id',
                'id'
            ),array(
                'supplierpayaccount.supplier_id',
                'supplier_id'
            ),array(
                'supplierpayaccount.payways_id',
                'payways_id'
            ),array(
                'supplierpayaccount.payaccountinfo_id',
                'payaccountinfo_id'
            ),array(
                'supplierpayaccount.active_status',
                'active_status'
            ),array(
                'supplierpayaccount.check_status',
                'check_status'
            ),array(
                'supplierpayaccount.check_id',
                'check_id'
            ),array(
                'supplierpayaccount.check_remark',
                'check_remark'
            ),array(
                'payaccountinfo.bankname',
                'bankname'
            ),array(
                'payaccountinfo.banklocation',
                'banklocation'
            ),array(
                'payaccountinfo.bankaccountname',
                'bankaccountname'
            ),array(
                'payaccountinfo.bankaccount',
                'bankaccount'
            ),array(//供应商二次新增字段
                'payaccountinfo.coinid',
                'coinid'
            ),array(
            'payaccountinfo.bankaddress',
            'bankaddress'
            ),array(
            'payaccountinfo.bankmanaddress',
            'bankmanaddress'
            ),array(
            'payaccountinfo.bankswift',
            'bankswift'
            ),array(
                'payways.paywayname',
                'paywayname'
            ));

        /**
         * 使用左链接
         */
        $re = $re->from('supplierpayaccount')
            ->join('payaccountinfo','LEFT')
            ->on('supplierpayaccount.payaccountinfo_id','=','payaccountinfo.id')
            ->join('payways','LEFT')
            ->on('supplierpayaccount.payways_id','=','payways.id');

        /**
         *
         */
        if(isset($condtion['id'])){
            $re = $re->where('supplierpayaccount.id','=',$condtion['id']);
        }
        if(isset($condtion['supplier_id'])){
            $re = $re->where('supplierpayaccount.supplier_id','=',$condtion['supplier_id']);
        }

        if(isset($condtion['supplier_name'])){

            $supplier_ids = Newerpclientapi::getSuppliers(array('id'),array('name'=>' LIKE "%'.trim($condtion['supplier_name']).'%"'));

            if($supplier_ids)
            {
                $supplier_ids = Arr::pluck($supplier_ids,'id');
            }
            else
            {
                $supplier_ids = array(-1);
            }
            $re = $re->where('supplierpayaccount.supplier_id','in',$supplier_ids);
        }
        if(isset($condtion['payways_id'])){
            $re = $re->where('supplierpayaccount.payways_id','=',$condtion['payways_id']);
        }
        if(isset($condtion['payaccountinfo_id'])){
            $re = $re->where('supplierpayaccount.payaccountinfo_id','=',$condtion['payaccountinfo_id']);
        }
        if(isset($condtion['active_status'])){
            $re = $re->where('supplierpayaccount.active_status','=',$condtion['active_status']);
        }
        if(isset($condtion['check_status'])){
            $re = $re->where('supplierpayaccount.check_status','=',$condtion['check_status']);
        }
        if(isset($condtion['check_id'])){
            $re = $re->where('supplierpayaccount.check_id','=',$condtion['check_id']);
        }
        if(isset($condtion['check_remark'])){
            $re = $re->where('supplierpayaccount.check_remark','LIKE',$condtion['check_remark']);
        }

        /**
         *
         */
        if(isset($condtion['bankname'])){
            $re = $re->where('payaccountinfo.bankname','LIKE',$condtion['bankname']);
        }

        if(isset($condtion['bankaccountname'])){
            $re = $re->where('payaccountinfo.bankaccountname','LIKE',$condtion['bankaccountname']);
        }

        if(isset($condtion['bankaccount'])){
            $re = $re->where('payaccountinfo.bankaccount','LIKE',$condtion['bankaccount']);
        }
        if(isset($condtion['coinid'])){
            $re = $re->where('payaccountinfo.coinid','LIKE',$condtion['coinid']);
        }

        if(isset($condtion['limit'])){
            $re = $re->limit($condtion['limit']);
        }

        if(isset($condtion['offset'])){
            $re = $re->offset($condtion['offset']);
        }

        /*echo $re->compile('newerp');*/

        $re = $re->execute('newerp')
            ->as_array();

        return $re;
    }

    /**
     * 转换信息到视图数据
     * @param array $datas
     * @return null $datas
     */
    public static function datas_to_views(array $datas = NULL)
    {
        if(empty($datas)){
            return NULL;
        }

        //获取币种名称
        $coins_arr = supplierbank::getCoins_arr();

        foreach($datas as $key => $data){
            if($data['active_status']==1){
                $datas[$key]['active_status_string'] = '使用';
            }elseif($data['active_status']==9){
                $datas[$key]['active_status_string'] = '停用';
            }

            if($data['check_status']==1){
                $datas[$key]['check_status_string'] = '待审核';
            }elseif($data['check_status']==5){
                $datas[$key]['check_status_string'] = '已审核';
            }elseif($data['check_status']==9){
                $datas[$key]['check_status_string'] = '未通过';
            }
            $datas[$key]['coins_name'] = $coins_arr[$data['coinid']];

            $supplier_id = isset($data['supplier_id'])?$data['supplier_id']:-1;
            $supplier_name = Newerpclientapi::getSuppliers(array('name'),array('id'=>"=".$supplier_id));
            $datas[$key]['supplier_name'] = isset($supplier_name[0]['name'])?$supplier_name[0]['name']:'';
        }

        return $datas;
    }

    /**
     * 处理修改,单条修改数据
     * @param array $update_data
     * @return null
     */
    public static function do_update(array $update_data = NULL)
    {
        if(empty($update_data) or !isset($update_data['id']) or !isset($update_data['payaccountinfo_id'])){
            return NULL;
        }

        $payaccountinfo_id = self::do_select(array(
            'id'                => $update_data['id'],
            'payaccountinfo_id' => $update_data['payaccountinfo_id']
        ));
        if(empty($payaccountinfo_id) or !isset($payaccountinfo_id[0]['id']) or !isset($payaccountinfo_id[0]['payaccountinfo_id'])){
            return NULL;
        }

        $time = date('Y-m-d H:i:s');

        $supplierpayaccount_up_data = array();
        if(isset($update_data['active_status'])){
            $supplierpayaccount_up_data['active_status'] = $update_data['active_status'];
        }
        if(isset($update_data['payways_id'])){
            $supplierpayaccount_up_data['payways_id'] = $update_data['payways_id'];
        }
        if(isset($update_data['check_status'])){
            $supplierpayaccount_up_data['check_status'] = $update_data['check_status'];
        }
        if(isset($update_data['check_id'])){
            $supplierpayaccount_up_data['check_id'] = $update_data['check_id'];
        }
        if(isset($update_data['check_remark'])){
            $supplierpayaccount_up_data['check_remark'] = $update_data['check_remark'];
        }

        if($supplierpayaccount_up_data and isset($payaccountinfo_id[0]['id'])){
            $supplierpayaccount_up_data['updatetime'] = $time;

            $supplierpayaccount_ok = DB::update('supplierpayaccount')
                ->set($supplierpayaccount_up_data)
                ->where('id','=',$payaccountinfo_id[0]['id']);
            $supplierpayaccount_ok = $supplierpayaccount_ok->execute('newerp');

            if(!isset($supplierpayaccount_ok) or $supplierpayaccount_ok==0){
                return NULL;
            }
        }

        $payaccountinfo_up_datas = array();
        if(isset($update_data['bankname'])){
            $payaccountinfo_up_datas['bankname'] = $update_data['bankname'];
        }
        if(isset($update_datas['bankaccountname'])){
            $payaccountinfo_up_datas['bankaccountname'] = $update_data['bankaccountname'];
        }
        if(isset($update_data['bankaccount'])){
            $payaccountinfo_up_datas['bankaccount'] = $update_data['bankaccount'];
        }

        if($payaccountinfo_up_datas and isset($update_data['payaccountinfo_id'])){
            $payaccountinfo_up_datas['updatetime'] = $time;

            $payaccountinfo_ok = DB::update('payaccountinfo')
                ->set($payaccountinfo_up_datas)
                ->where('id','=',($update_data['payaccountinfo_id']));
            //echo $payaccountinfo_ok;exit;
            $payaccountinfo_ok = $payaccountinfo_ok->execute('newerp');

            if(!isset($payaccountinfo_ok) or $payaccountinfo_ok==0){
                return NULL;
            }
        }

        return $payaccountinfo_id[0]['id'];
    }

    /**
     * 处理插入数据，使用批量插入信息
     * @param array $insert_datas
     */
    public static function insert_to_newerp(array $insert_datas = NULL)
    {
    }

    /**
     * 从sku基础资料系统获取供应商信息
     * @param array $supp_id
     */
/*    public static function get_supplier_info_remote(array $supp_id = NULL)
    {
        $filed = array('id','name','address','website','passport','boss','bossphone','remark','createtime','modifytime');
        $contact_filed =
        $supplier_info = Newerpclientapi::getSuppliers($filed,array(''));
        $contact_info = Newerpclientapi::getSupplierContacts($supp_id);
    }*/

    /**
     * 处理添加供应商银行帐号信息
     * @pram array
     */
    public static function do_add_supplier_bank(array $add_datas = NULL)
    {
        if(empty($add_datas)){
            return NULL;
        }

        if(!isset($add_datas['bankname']) or !isset($add_datas['bankaccountname']) or !isset($add_datas['bankaccount']) or !isset($add_datas['supplier_id']) or !isset($add_datas['payways_id'])){
            return NULL;
        }
        /**
         * 获取关键信息，银行帐号信息,
         * 不能为空了
         */
        $time                                           = date('Y-m-d H:i:s');
        $payaccountinfo_insert_datas                    = array();
        $payaccountinfo_insert_datas['bankname']        = $add_datas['bankname'];
        $payaccountinfo_insert_datas['bankaccountname'] = $add_datas['bankaccountname'];
        $payaccountinfo_insert_datas['bankaccount']     = $add_datas['bankaccount'];
        $payaccountinfo_insert_datas['createtime']      = $time;
        $payaccountinfo_insert_datas['updatetime']      = $time;
        $payaccountinfo_insert                          = DB::insert('payaccountinfo',array_keys($payaccountinfo_insert_datas))
            ->values(array_values($payaccountinfo_insert_datas));
        list($payaccountinfo_insert_id,) = $payaccountinfo_insert->execute('newerp');

        if(!isset($payaccountinfo_insert_id) or $payaccountinfo_insert_id==0){
            return NULL;
        }
        /**
         * 获取关键数据,不能为空
         */
        $supplierpayaccount_insert_datas                      = array();
        $supplierpayaccount_insert_datas['supplier_id']       = $add_datas['supplier_id'];
        $supplierpayaccount_insert_datas['payways_id']        = $add_datas['payways_id'];
        $supplierpayaccount_insert_datas['payaccountinfo_id'] = $payaccountinfo_insert_id;
        $supplierpayaccount_insert_datas['active_status']     = 1;
        $supplierpayaccount_insert_datas['check_status']      = 1;
        $supplierpayaccount_insert_datas['check_id']          = 0;
        $supplierpayaccount_insert_datas['check_remark']      = '';
        $supplierpayaccount_insert_datas['createtime']        = $time;
        $supplierpayaccount_insert_datas['updatetime']        = $time;

        $supplierpayaccount_insert = DB::insert('supplierpayaccount',array_keys($supplierpayaccount_insert_datas))
            ->values(array_values($supplierpayaccount_insert_datas));
        list($supplierpayaccount_insert_id,) = $supplierpayaccount_insert->execute('newerp');

        if(isset($supplierpayaccount_insert_id) and $supplierpayaccount_insert_id>0){
            return $supplierpayaccount_insert_id;
        }
    }


    /**
     * 获取老ERP的数据了
     * @return mixed
     */
    public static function get_bankinfos_from_erp()
    {
        $sql_string = ' SELECT erp_provider.id,
        ifnull(erp_provider.vEstablishBank,\'\') as vEstablishBank,
        ifnull(erp_provider.vAccount,\'\') as vAccount,
        ifnull(erp_provider.vAccountname,\'\') as vAccountname,
        ifnull(erp_pay_type.id,0) as payway
        FROM erp_provider
        LEFT  JOIN erp_pay_type ON erp_provider.payment = erp_pay_type.type';

        /**
         * 只同步已经通过审核的供应商
         */
        $sql_string .= ' WHERE erp_provider.state = 2 ';

        $re = DB::query(Database::SELECT,$sql_string)
            ->execute('readonlyerp')
            ->as_array();

        return $re;
    }


    /**
     * 获取老ERP的供应商银行帐号信息
     */
    /*static function get_from_erp()
    {
        $sql_string = ' SELECT erp_provider.id,
        ifnull(erp_provider.vEstablishBank,\'\') as vEstablishBank,
        ifnull(erp_provider.vAccount,\'\') as vAccount,
        ifnull(erp_provider.vAccountname,\'\') as vAccountname,
        ifnull(erp_pay_type.id,0) as payway
        FROM erp_provider
        LEFT  JOIN erp_pay_type ON erp_provider.payment = erp_pay_type.type';

        $re = DB::query(Database::SELECT,$sql_string)
            ->execute('readonlyerp')
            ->as_array();

        $date = date('Y-m-d H:i:s');

        if($re){
            foreach($re as $key => $value){
                $insert_data_tmp   = array(
                    'bankname'        => (isset($value['vEstablishBank'])?$value['vEstablishBank']:''),
                    'bankaccountname' => (isset($value['vAccountname'])?$value['vAccountname']:''),
                    'bankaccount'     => (isset($value['vAccount'])?$value['vAccount']:''),
                    'createtime'      => $date,
                    'updatetime'      => $date,
                    'status'          => 1
                );
                $payaccountinfo_id = DB::insert('payaccountinfo',array_keys($insert_data_tmp))
                    ->values($insert_data_tmp)
                    ->execute('newerp');
                if(isset($payaccountinfo_id[0]) and $payaccountinfo_id[0]>0){
                    $supplierpayaccount_insert_data = array(
                        'suppplier_id'      => (isset($value['id'])?$value['id']:0),
                        'payways_id'        => (isset($value['payway'])?$value['payway']:0),
                        'payaccountinfo_id' => $payaccountinfo_id[0],
                        'status'            => 1,
                        'createtime'        => $date,
                    );
                    $supplierpayaccount_id          = DB::insert('supplierpayaccount',array_keys($supplierpayaccount_insert_data))
                        ->values($supplierpayaccount_insert_data)
                        ->execute('newerp');
                    if(!isset($supplierpayaccount_id[1])){
                        continue;
                    }
                }else{
                    continue;
                }
            }
        }
    }*/

    /**
     * 批量插入数据
     * @param array $insert_data
     */
    static function insert_bankinfos_newerp_bat(array $insert_data=NULL)
    {

        if($insert_data){
            $date = date('Y-m-d H:i:s');
            foreach($insert_data as $key => $value){

                $insert_data_tmp   = array(
                    'bankname'        => (isset($value['vEstablishBank'])?$value['vEstablishBank']:''),
                    'bankaccountname' => (isset($value['vAccountname'])?$value['vAccountname']:''),
                    'bankaccount'     => (isset($value['vAccount'])?$value['vAccount']:''),
                    'createtime'      => $date,
                    'updatetime'      => $date,
                );
                $payaccountinfo_id = DB::insert('payaccountinfo',array_keys($insert_data_tmp))
                    ->values($insert_data_tmp)
                    ->execute('newerp');

                $supplierpayaccount_insert_data = array(
                        'supplier_id'      => (isset($value['id'])?$value['id']:0),
                        'payways_id'        => (isset($value['payway'])?$value['payway']:0),
                        'payaccountinfo_id' => isset($payaccountinfo_id[0])?$payaccountinfo_id[0]:0,
                        'active_status'     => 1,
                        'check_status'      => 5,
                        'check_id'          => 0,
                        'updatetime'        => $date,
                        'createtime'        => $date,
                );

                $supplierpayaccount_id  = DB::insert('supplierpayaccount',array_keys($supplierpayaccount_insert_data))
                        ->values($supplierpayaccount_insert_data)
                        ->execute('newerp');
            }
        }
    }

    /**
     * 更新信息
     * @param array $update_dates
     */
    static function update_bankinfos_newerp_bat(array $update_dates=NULL)
    {

        if($update_dates){
            $date = date('Y-m-d H:i:s');

            foreach($update_dates as $key => $value){

                /**
                 * 供应商ID
                 */
                $supplier_id = isset($value['id'])?$value['id']:-1;

                $exits_info = DB::select(
                    array('payaccountinfo.id','id'),
                    array('payaccountinfo.bankname','bankname'),
                    array('payaccountinfo.bankaccountname','bankaccountname'),
                    array('payaccountinfo.bankaccount','bankaccount')
                )->from('supplierpayaccount')
                    ->join('payaccountinfo')
                    ->on('supplierpayaccount.payaccountinfo_id','=','payaccountinfo.id')
                    ->where('supplierpayaccount.supplier_id','=',$supplier_id)
                    ->execute('newerp')->current();

                var_dump($exits_info);echo "<br/>";
                if(isset($exits_info['id']) and $exits_info['id'] > 0)
                {
                     if(($value['vEstablishBank'] != $exits_info['bankname'])
                         or ($value['vAccountname'] != $exits_info['bankaccountname'])
                         or ($value['vAccount'] != $exits_info['bankaccount']))
                     {
                         /**
                          * 更新的数据
                          */
                         $update_data_tmp   = array(
                             'bankname'        => (isset($value['vEstablishBank'])?$value['vEstablishBank']:''),
                             'bankaccountname' => (isset($value['vAccountname'])?$value['vAccountname']:''),
                             'bankaccount'     => (isset($value['vAccount'])?$value['vAccount']:''),
                             'updatetime'      => $date,
                         );
                         echo "不相同";
                         var_dump($update_data_tmp);echo "<br/>";
                         DB::update('payaccountinfo')
                             ->set($update_data_tmp)
                             ->where('id','=',$exits_info['id'])->execute('newerp');
                     }

                }
            }
        }
    }

    /**
     * 通过供应商id查询供应商付款方式信息
     * @param $supplier_id
     * @param $active_status
     * @return array
     */
    public static function get_supplier_payways_by_supplier_id($supplier_id,$active_status = true)
    {
        $url = Kohana::$config->load('api_url')->get('getSupplierBankInfo');
        $data = array('supplierIds' => $supplier_id);
        $handle = curl_init();
        curl_setopt($handle,CURLOPT_URL,$url);
        curl_setopt($handle,CURLOPT_RETURNTRANSFER,TRUE);
        curl_setopt($handle,CURLOPT_USERAGENT,'Fbawarehouse API/1.0');
        curl_setopt($handle,CURLOPT_CONNECTTIMEOUT,60);
        curl_setopt($handle,CURLOPT_TIMEOUT,90);
        curl_setopt($handle,CURLOPT_MAXREDIRS,3);
        curl_setopt($handle,CURLOPT_POST,TRUE);
        curl_setopt($handle,CURLOPT_POSTFIELDS,http_build_query($data));
        curl_setopt($handle,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_0);
        curl_setopt($handle,CURLOPT_HEADER,FALSE);    //不返回头信息
        $response = curl_exec($handle);
        $response = json_decode($response,true);
        return $response['data'];
    }

    /**
     * 根据供应商的id'查询供应商付款帐号信息
     * @param      $supplier_id
     * @param bool $active_status
     * @return array
     */
    public static function get_supplier_bankinfo_by_supplier_id($supplier_id,$active_status=true)
    {
        $re = DB::select('payaccountinfo_id','bankname','bankaccountname','bankaccount')->from('supplierpayaccount');
        $re = $re->join('payaccountinfo')->on('supplierpayaccount.payaccountinfo_id','=','payaccountinfo.id');
        $re = $re->where('supplierpayaccount.supplier_id','=',$supplier_id);
        $re = $re->where('supplierpayaccount.check_status','=',5);

        if($active_status)
        {
            $re = $re->where('supplierpayaccount.active_status','=',1);
        }
        $re = $re->execute('newerp')->as_array();

        return $re;
    }

    /**
     * 根据供应商的id'查询供应商付款帐号信息
     * @param      $supplier_id
     * @param bool $active_status
     * @return array
     */
    public static function get_supplier_bankinfo_by_supplier_id_new($supplier_id,$active_status=true)
    {
        $re = DB::select('payaccountinfo_id','coinid', 'bankname', 'bankaddress', 'bankaccountname', 'bankaccount', 'bankmanaddress', 'bankswift')->from('supplierpayaccount');
        $re = $re->join('payaccountinfo')->on('supplierpayaccount.payaccountinfo_id','=','payaccountinfo.id');
        $re = $re->where('supplierpayaccount.supplier_id','=',$supplier_id);
        $re = $re->where('supplierpayaccount.check_status','=',5);

        if($active_status)
        {
            $re = $re->where('supplierpayaccount.active_status','=',1);
        }
        $re = $re->execute('newerp')->as_array();

        return $re;
    }

    /**
     * @param null $fields
     * @return mixed
     * 从供应商应付账款系统获取币种信息
     */
    public static function getCoins($fields = NULL) {
        if(empty($fields)){
            $cols = "id, name";
        }elseif(is_array($fields)){
            $cols = join(",", $fields);
        }

        return Acsystemclient::getAccountSystemDataBySql("SELECT {$cols} FROM coins");
    }

    /**
     * @param null $fields
     * @return mixed
     * 从供应商应付账款系统获取币种信息
     */
    public static function getCoins_arr($fields = NULL) {
        if(empty($fields)){
            $cols = "id, name";
        }elseif(is_array($fields)){
            $cols = join(",", $fields);
        }

        $coins = Acsystemclient::getAccountSystemDataBySql("SELECT {$cols} FROM coins");
        $coins_arr = array();
        foreach($coins as $val){
            $coins_arr[$val['id']] = $val['name'];
        }
        return $coins_arr;
    }
}